﻿using FastCode.Architecture;
using FastCode.DTO;
using FastCode.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Reflection;
using System.Text;
//using IOFile = System.IO;
using IOFile = System.IO.File;
namespace FastCode.Controllers
{
    public class GenerageCodeController : ApiPureController
    {

        /// <summary>
        /// 生成后端api和前端页面
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GeApiAndFront(DBConfigDTO dto)
        {
            string currentDirectory = Directory.GetCurrentDirectory();

            var p1 = Directory.GetParent(currentDirectory);
            var projectPath = Directory.GetParent(currentDirectory)?.Parent;
            var frontViewsPath = projectPath?.FullName + "\\FrontEnd\\src\\views";
            var srcPath = projectPath?.FullName + "\\FrontEnd\\src\\";

            var templateContent = await IOFile.ReadAllTextAsync(currentDirectory + "/T4Template/FastCodeController.txt");
            templateContent = templateContent.Replace("{TableName}", dto.TableName);
            await IOFile.WriteAllTextAsync($"{currentDirectory}/Controllers/{dto.TableName}Controller.cs", templateContent);


            var vueContent = await IOFile.ReadAllTextAsync($"{frontViewsPath}/CURDTemplate.vue");

            vueContent = vueContent.Replace("CURDTemplate", dto.TableName);
            //写入前端
            await IOFile.WriteAllTextAsync($"{frontViewsPath}/{dto.TableName}.vue", vueContent);


            //配置路由
            var routerConfigPath = $"{srcPath}/router/routersConfig.js";
            ///src/views/{dto.TableName}.vue 如果已经包含此页面( 重复点击 )
            var routerContent = await IOFile.ReadAllTextAsync(routerConfigPath);
            var pagePath = $"/src/views/{dto.TableName}.vue";
            if (!routerContent.Contains(pagePath))
            {
                var newPageConfigRoute = $"  {{\r\n    path: '/{dto.TableName?.ToLower()}',\r\n    label: '{dto.TableName}',\r\n    component: () => import(\"{pagePath}\"),\r\n  }},\r\n];";
                routerContent = routerContent.Replace("];", newPageConfigRoute);
                await IOFile.WriteAllTextAsync(routerConfigPath, routerContent);
            }

            return Msg.Success(null, "ok");
        }

    }
}
